package com.hanthink.common.utils.file;

import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.imageio.ImageIO;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import net.coobird.thumbnailator.Thumbnails;

/**
* <p>Title: ImageUtils</p>  
* <p>Description: 图像工具类</p>  
* @author vondser
* @date 2020年12月22日
 */
public class ImageUtils {
	
	protected final static Logger logger = LoggerFactory.getLogger(ImageUtils.class);
	
	// 压缩率
	private static final transient float IMAGE_RATIO = 0.2f;
	
	// 压缩最大宽度
	private static final transient int IMAGE_WIDTH = 1080;

	/**
	 * 压缩图像
	 * 
	 * @param image
	 * @return
	 * @throws IOException
	 */
	public static BufferedImage compress(BufferedImage image) throws IOException {
        Thumbnails.Builder<BufferedImage> imageBuilder= Thumbnails.of(image).outputQuality(IMAGE_RATIO);
        if(image.getWidth()>IMAGE_WIDTH){
            return imageBuilder.width(IMAGE_WIDTH).asBufferedImage();
        }
        else {
            return imageBuilder.scale(1).asBufferedImage();
        }
	}

	/**
	 * 根据文件扩展名判断文件是否图片格式
	 * 
	 * @return
	 */
	public static boolean isImage(String fileName) {
		String[] imageExtension = new String[] { "bmp", "dib", "gif", "jfif", "jpe", "jpeg", "jpg", "png", "tif", "tiff" };

		for (String e : imageExtension)
			if (getFileExtention(fileName).toLowerCase().equals(e))
				return true;

		return false;
	}
	
	/**
	 * 根据文件扩展名判断文件是否视频格式
	 * 
	 * @return
	 */
	public static boolean isVideo(String fileName) {
		String[] imageExtension = new String[] { "mp4", "mkv", "rmvb", "webm", "flv", "3gp", "avi", "wmv"};

		for (String e : imageExtension)
			if (getFileExtention(fileName).toLowerCase().equals(e))
				return true;

		return false;
	}

	/**
	 * 获取文件后缀名称
	 * 
	 * @param fileName
	 * @return
	 */
	public static String getFileExtention(String fileName) {
		String extension = fileName.substring(fileName.lastIndexOf(".") + 1);
		return extension;
	}

	/**
	 * 根据图片对象获取对应InputStream
	 *
	 * @param image
	 * @param readImageFormat
	 * @return
	 * @throws IOException
	 */
	public static InputStream getInputStream(BufferedImage image, String readImageFormat) throws IOException {
		ByteArrayOutputStream os = new ByteArrayOutputStream();
		ImageIO.write(image, readImageFormat, os);
		InputStream is = new ByteArrayInputStream(os.toByteArray());
		os.close();
		return is;
	}
}